package com.scs.application.modules.print.sync.impl;

import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.utils.BeanUtils;
import com.scs.application.modules.print.adapter.PrintTemplateAdapter;
import com.scs.application.modules.print.dto.TemplateDTO;
import com.scs.application.modules.print.entity.Field;
import com.scs.application.modules.print.entity.Template;
import com.scs.application.modules.print.service.TemplateService;
import com.scs.application.modules.print.sync.PrintTemplateSyncService;
import com.scs.application.modules.sys.properties.SystemProperties;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description:打印模板同步实现
 */
@Service
@Slf4j
public class PrintTemplateSyncServiceImpl implements PrintTemplateSyncService {

    @Autowired
    private SystemProperties systemProperties;

    @Autowired
    private PrintTemplateAdapter printTemplateAdapter;

    /**
     * 同步打印模板
     */
    @Override
    public void syncPrintTemplate() {
        TemplateService fileTemplateService = printTemplateAdapter.getTemplateService(false);
        List<TemplateDTO> fileTemplateDTOs = fileTemplateService.getDTOList();
        if (fileTemplateDTOs == null || fileTemplateDTOs.isEmpty()) {
            return;
        }
        List<Template> needUpdateTemplates = Lists.newArrayList();
        List<Field> needUpdateFields = Lists.newArrayList();
        List<Template> templates = printTemplateAdapter.getTemplateService().list();
        for (TemplateDTO templateDTO : fileTemplateDTOs) {
            if (!templates.stream().anyMatch(template -> templateDTO.getBusType().equalsIgnoreCase(template.getBusType()))) {
                Template template = new Template();
                BeanUtils.copyProperties(templateDTO, template);
                needUpdateTemplates.add(template);

                if (CollectionUtils.isNotEmpty(templateDTO.getFieldDTOS())) {
                    templateDTO.getFieldDTOS().forEach(fieldDTO -> {
                        Field field = new Field();
                        BeanUtils.copyProperties(fieldDTO, field);
                        needUpdateFields.add(field);
                    });
                }
            }
        }

        if (needUpdateTemplates.size() > 0) {
            printTemplateAdapter.getTemplateService().saveBatch(needUpdateTemplates);
        }
        if (needUpdateFields.size() > 0) {
            try {
                needUpdateFields.stream().forEach(field -> {
                    printTemplateAdapter.getFieldService().saveOrUpdate(field);
                });
            } catch (Exception ex) {
                throw new BusinessException(ex.getMessage());
            }
        }
    }
}
